package system.self.defined;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.web.mymvc.common.SystemInterface;
import com.freedom.web.mymvc.utils.ByteBufUtils;
import com.freedom.web.mymvc.utils.ConstantsUtils;
import com.freedom.web.mymvc.utils.FileUtils;
import com.freedom.web.mymvc.utils.LoggerUtils;
import com.freedom.web.mymvc.utils.UriUtils;
import com.freedom.web.mymvc.view.ModelAndView;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.CharsetUtil;

public class StaticResource implements SystemInterface {

	// logger
	private static final Logger logger = LogManager.getLogger(StaticResource.class);
	private static String resourcePrefix = System.getProperty("resourcePrefix", "src/main/resources");

	@Override
	public ModelAndView service(FullHttpRequest request, FullHttpResponse response) throws Exception {
		LoggerUtils.debug(logger, "StaticResource.service invoked...by [" + request.getMethod() + " " + request.getUri()
				+ " " + request.getProtocolVersion());
		// 1)提取出request的内容
		String method = request.getMethod().toString();
		String requestUri = UriUtils.parseUri(request.getUri());
		String httpVersion = request.getProtocolVersion().toString();
		HttpHeaders head = request.headers();
		String requestBody = ByteBufUtils.getContent(request.content());
		// 2)设置response,因为是静态文件，所以自己负责输出文件到response,包括设置header&response
		{

			// header
			String fileType = FileUtils.getFileType(requestUri);
			if (null != fileType) {
				response.headers().set(CONTENT_TYPE, fileType);
			}
			// content
			String fileContent = FileUtils.getFileContent(resourcePrefix + requestUri);
			ByteBuf buffer = Unpooled.copiedBuffer(fileContent, CharsetUtil.UTF_8);
			response.content().writeBytes(buffer);
			buffer.release();// 务必要释放buffer
			// response.headers().set(CONTENT_TYPE, MyConstants.JSON);
		}
		// null表示不需要渲染
		return null;

		// 多说几句
		// 关于某些敏感资源，在tomcat中，是通过URL内部包含特定字符串则不容许通过的方式解决的
		// 用户可以以此展开
	}

}
